package com.jixi.handler;

import cn.dev33.satoken.exception.NotLoginException;
import com.jixi.common.constant.ResultCodeConstant;
import com.jixi.common.exception.BaseException;
import com.jixi.common.exception.FileUploadException;
import com.jixi.common.exception.HttpRequestException;
import com.jixi.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler extends BaseException {
	
	@ExceptionHandler(Exception.class)
	@ResponseBody
	public Result error(Exception e) {
		log.error(e.getMessage());
		return Result.fail(ResultCodeConstant.FAIL, e.getMessage());
	}
	
	@ExceptionHandler(BaseException.class)
	@ResponseBody
	public Result error(BaseException e) {
		log.error(e.getMessage());
		return Result.fail(e.getCode(), e.getMessage());
	}
	
	@ExceptionHandler(NotLoginException.class)
	@ResponseBody
	public Result error(NotLoginException e) {
		log.error(e.getMessage());
		return Result.fail(ResultCodeConstant.NOT_LOGIN, e.getMessage());
	}
	
	/**
	 * 唯一字段异常捕获器
	 *
	 * @param ex 异常
	 * @return 返回消息
	 */
	@ExceptionHandler(DuplicateKeyException.class)
	@ResponseBody
	public Result handleDuplicateKeyException(DuplicateKeyException ex) {
		if (ex.getRootCause().getMessage().contains("education.education_username_unique") ||
				ex.getRootCause().getMessage().contains("company.company_username_unique") ||
				ex.getRootCause().getMessage().contains("school.unique1")) {
			log.error("用户名唯一字段异常信息: {}", ex.getMessage());
			return Result.fail("该用户名已被注册，请更换其他用户名");
		} else if (ex.getRootCause().getMessage().contains("account.unique1")) {
			log.error("银行账户卡号唯一字段异常信息: {}", ex.getMessage());
			return Result.fail("该银行账户卡号已被注册，请更换其他银行账户卡号");
		}
		log.error("其他唯一字段异常信息: {}", ex.getMessage());
		return Result.fail("服务异常，请联系管理员。异常信息: 唯一字段异常");
	}
	
	/**
	 * Null指针异常捕获器
	 *
	 * @param ex 异常
	 * @return 返回消息
	 */
	@ExceptionHandler(NullPointerException.class)
	@ResponseBody
	public Result handleNullPointerException(NullPointerException ex) {
		log.error("空指针异常信息: {}", ex.getMessage(), ex);
		return Result.fail("服务异常，请联系管理员。异常信息: 空指针异常");
	}
	
	/**
	 * HTTP请求异常捕获器
	 *
	 * @param ex 异常
	 * @return 返回消息
	 */
	@ExceptionHandler(HttpRequestException.class)
	@ResponseBody
	public Result handleHttpRequestException(HttpRequestException ex) {
		log.error("HTTP（CozeAPI）请求异常信息: {}", ex.getMessage(), ex);
		return Result.fail("COZE服务异常，请联系管理员。异常信息: 后端HTTP请求异常");
	}
	
	/**
	 * 文件上传异常捕获器
	 *
	 * @param ex 异常
	 * @return 返回消息
	 */
	@ExceptionHandler(FileUploadException.class)
	@ResponseBody
	public Result handleFileUploadException(FileUploadException ex) {
		log.error("文件上传异常信息: {}", ex.getMessage(), ex);
		return Result.fail("文件上传失败，请检查您的文件后重试。或联系管理员。异常信息: 文件上传异常");
	}
}
